package com.shelpe.services.sustainer.autoDrive;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.batch.item.ItemReader;

import com.shelpe.services.sustainer.entity.jpa.AutoProductQueue;
import com.shelpe.services.sustainer.entity.jpa.InprogressAutoDriver;
import com.shelpe.services.sustainer.repository.jpa.InprogressAutoDriverRepository;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
public class InprogressDriverReader implements ItemReader<AutoProductQueueInput>{

	private List<AutoProductQueueInput> list;
	private int step;
	private String jobName;
	private InprogressAutoDriverRepository inprogressAutoDriverRepository;
	private InprogressJobs inprogressJobs;
	
	public InprogressDriverReader(String job, int step){
		this.step = step;
		this.jobName = job;
	}
	
    @Override
	public AutoProductQueueInput read() {
    	if(this.list == null){
    		init();
    	}
    	
		if (!list.isEmpty()) {
			return list.remove(0);
		}
		return null;
	}
    
    private void init(){
    	this.list = new ArrayList<AutoProductQueueInput>();
    	
		InprogressAutoDriver driver = this.inprogressAutoDriverRepository.findTopByStepAndDoneOrderByProductsAsc(step, 0);
		log.debug("step {} InprogressAutoDriver: {}", step, driver);
		if(driver != null && driver.getProductIDs() != null){
			String driverID = driver.getCampaignID() + "-" + driver.getStep() + "-" + driver.getChunk();
			if(this.inprogressJobs.contain(jobName, driverID)){
				log.debug("the driver {} is already by registered by other in job {}", driver, jobName);
				return;
			}
			if(driver.getProducts() > 5 && this.inprogressJobs.hasFewJobsJob(jobName)){
				log.debug("the driver {} is more than 5 products in job {} and there is another few-products job", driver, jobName);
				return;
			}
			
			String[] ids = driver.getProductIDs().split("\\|");
			for(String id: ids){
				if(NumberUtils.isNumber(id)){
					AutoProductQueue.QueuePK pk = new AutoProductQueue.QueuePK();
					pk.setCampaignID(driver.getCampaignID());
					pk.setProductID(NumberUtils.toLong(id));
					AutoProductQueueInput input = new AutoProductQueueInput();
					input.setPk(pk);
					input.setChunk(driver.getChunk());
					this.list.add(input);
				}
			}
			this.inprogressJobs.registerDriver(jobName, driverID, driver.getProducts());
		}
    }
	
}
